package com.snow.springboot.task;

import com.snow.springboot.entity.NcmsInfo;
import com.snow.springboot.service.NcmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Package: com.snow.springboot.task
 * @ClassName: ConsumeNcmsTask
 * @Description:
 * @author: lurui
 * @Date: 2018/10/24 下午2:45
 * @version:
 */
public class ConsumeNcmsTask implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConsumeNcmsTask.class);

    private BlockingQueue<NcmsInfo> queue;

    private NcmsService ncmsService;

    public ConsumeNcmsTask(BlockingQueue<NcmsInfo> queue, NcmsService ncmsService) {
        this.queue = queue;
        this.ncmsService = ncmsService;
    }

    @Override
    public void run() {
        LOGGER.info("consume data!");
        NcmsInfo ncmsInfo = null;
        boolean flag = true;
        try {
            while (flag) {
                ncmsInfo = queue.poll(60, TimeUnit.SECONDS);
                if (ncmsInfo != null) {
                    ncmsService.saveNcmsInfo(ncmsInfo);
                } else {
                    flag = false;
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            LOGGER.error("consumeNcms error.{}", ncmsInfo.getCode());
            Thread.currentThread().interrupt();
        }
    }
}
